package zap

import (
	"fmt"
	"os"
	"path"
	"time"

	rotatelogs "github.com/lestrrat-go/file-rotatelogs"
	"go.uber.org/zap/zapcore"
)

func GetWriteSyncer(logcfg *Config, level string) (zapcore.WriteSyncer, error) {
	syncers := make([]zapcore.WriteSyncer, 0)

	if logcfg.LogInConsole {
		syncers = append(syncers, zapcore.AddSync(os.Stdout))
	}

	if logcfg.LogInFile {
		fileWriter, err := rotatelogs.New(
			path.Join(logcfg.Director, "%Y-%m-%d.log"), // 各级别保留到同一个日志文件中
			rotatelogs.WithClock(rotatelogs.Local),
			rotatelogs.WithMaxAge(time.Duration(logcfg.MaxAge)*24*time.Hour), // 日志留存时间
			rotatelogs.WithRotationTime(time.Hour*24),
		)
		if err != nil {
			fmt.Printf("fileWriter err: %v\n", err)
			return nil, err
		}
		syncers = append(syncers, zapcore.AddSync(fileWriter))
	}

	// 如果没有配置任何写入目标，默认返回一个空的 WriteSyncer
	if len(syncers) == 0 {
		return zapcore.AddSync(os.Stdout), nil
	}

	return zapcore.NewMultiWriteSyncer(syncers...), nil
}
